package com.student.service.impl;

import com.student.dto.ResponseDto;
import com.student.mapper.PhMenuMapper;
import com.student.pojo.PhMenuDO;
import com.student.service.PhMenuService;
import com.student.util.MeunUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @BelongsProject: public_house
 * @BelongsPackage: com.cykj.service.impl
 * @Author: 小徐
 * @CreateTime: 2024-11-06 15:59
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class PhMenuServiceImpl implements PhMenuService {
    @Autowired
    private PhMenuMapper phMenuMapper;
    @Override
    public ResponseDto getMenu(Integer roleId) {
//        角色对应的菜单栏
      List<PhMenuDO>  roleMeun= phMenuMapper.getMenu(roleId);
        List<PhMenuDO> listsRoleMenu = MeunUtils.getMeun(roleMeun);

        return ResponseDto.success(listsRoleMenu);

    }


    @Override
    public ResponseDto getAssignedMeun(Integer roleId) {
//        查询角色已经分配的菜单
        List<PhMenuDO>  AssignedMeun = phMenuMapper.getAssignedMeun(roleId);
        List<PhMenuDO> listsRoleMenu = MeunUtils.getMeun(AssignedMeun);

//        查看所有菜单
        List<PhMenuDO> allRole= phMenuMapper.getRoleName();
        List<PhMenuDO> fromData = MeunUtils.getMeun(allRole);

        fileterMenu(fromData,AssignedMeun);

        HashMap<String, Object> hashMap = new HashMap<>();

        hashMap.put("fromData", fromData);
        hashMap.put("toData", listsRoleMenu);

        return ResponseDto.success(hashMap);
    }



    //    过滤菜单的方法
    private void fileterMenu(List<PhMenuDO> fromData, List<PhMenuDO> listsRoleMenu) {
        Iterator<PhMenuDO> it = fromData.iterator();

        while (it.hasNext()) {
//            读取当前菜单
            PhMenuDO next = it.next();
//            没有子菜单
            if (next.getChildren().size() == 0) {
//            遍历已有菜单
                for (PhMenuDO roleMenu : listsRoleMenu) {
//                判断菜单id是否相等，相等就删除

                    if (next.getMenuId() == roleMenu.getMenuId()) {
                        it.remove();
                    }
                }
            } else {
//                有子菜单==》遍历子菜单
                fileterMenu(next.getChildren(), listsRoleMenu);
//如果没有子菜单就删除父级菜单
                if (next.getChildren().size() == 0) {
                    it.remove();
                }

            }
        }
    }

}